/**
 *
 * Description: 
 *
 * @author lirong
 * @version 1.0
 * <pre>
 * Modification History: 
 * Date         Author      Version     Description 
 * ------------------------------------------------------------------ 
 * 2012-3-15    lirong       1.0        1.0 Version 
 * </pre>
 */

package com.creditease.mobile.rss.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.*;
import android.webkit.WebView.HitTestResult;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.creditease.mobile.R;
import com.creditease.mobile.rss.RssConst;
import com.creditease.mobile.rss.dao.RssItemDB;
import com.creditease.mobile.rss.model.RssItemModel;
import com.creditease.mobile.util.CacheMgr;
import com.creditease.mobile.util.FileUtil;
import com.creditease.mobile.util.StreamUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description:
 *
 * @author lirong
 * @version 1.0
 */

public class RssReader extends Activity {
    private WebView webView;
    private float startX;
    private float endX;
    private String link;
    private TextView titleText;
    private String title;
    private RssItemDB db;
    private final String TAG = RssReader.class.getName();
    private ImageView titleView;
    private ImageView reflushView;
    private ProgressBar processbar;
    private ProgressBar loadingProcessbar;
    private String[] pics;
    private String rssTitle;
    private String articleLink;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

        setContentView(R.layout.rss_reader);
        // getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
        // R.layout.title);
        // 设置Home图标
        titleView = (ImageView) findViewById(R.id.titleIcon);
        Drawable drawable = getResources().getDrawable(R.drawable.icon_back);
        titleView.setAdjustViewBounds(true);
        titleView.setImageDrawable(drawable);
        titleView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                RssReader.this.onBackPressed();
            }
        });
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new MyJavaScript(),"rss");
        // webView.setInitialScale(100);
        // 支持缩放
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // webView.getSettings()

        Intent intent = getIntent();
        String url = intent.getExtras().getString("url");
        link = intent.getExtras().getString("link");
        title = intent.getExtras().getString("title");
        String id = intent.getExtras().getString("id");
        // String sectionId = intent.getExtras().getString("sectionId");
        db = new RssItemDB(getApplicationContext());
        // List<RssItemModel> items = CacheMgr.getList(sectionId);
        Log.d(TAG, "id=" + id);
        final RssItemModel bean = (RssItemModel) CacheMgr.get(id);// db.findById(id);

        // 刷新按钮不可见
        reflushView = (ImageView) findViewById(R.id.reflushIcon);
        reflushView.setAdjustViewBounds(true);
        reflushView.setBackgroundResource(R.drawable.listview_selector);
        if (bean.isFav) {
            Drawable drawable1 = getResources().getDrawable(R.drawable.menu_favorite);
            reflushView.setImageDrawable(drawable1);
        } else {
            Drawable drawable1 = getResources().getDrawable(R.drawable.menu_favorite_cancel);
            reflushView.setImageDrawable(drawable1);
        }
        reflushView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bean.isFav = !bean.isFav;
                bean.favTime = new Date().getTime();
                db.update(bean);
                if (bean.isFav) {
                    Drawable drawable1 = getResources().getDrawable(R.drawable.menu_favorite);
                    reflushView.setImageDrawable(drawable1);
                    Toast.makeText(getApplicationContext(), R.string.favOK, Toast.LENGTH_SHORT)
                            .show();
                } else {
                    Drawable drawable1 = getResources().getDrawable(R.drawable.menu_favorite_cancel);
                    reflushView.setImageDrawable(drawable1);
                    Toast.makeText(getApplicationContext(), R.string.favCannel, Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
        // 标题
        titleText = (TextView) findViewById(R.id.titleText);
        titleText.setText(title);
        StringBuilder buf = new StringBuilder();

        InputStream fisFileInputStream = null;
        try {
            rssTitle = bean.articleTitle;
            articleLink= bean.articleLink;
            fisFileInputStream = getApplication().getAssets().open("templete.html");
            String tempString = StreamUtil.stream2String(fisFileInputStream);
            tempString = tempString.replace("{ARTICLE_TITLE}", bean.articleTitle);
            tempString = tempString.replace("{SECTION_NAME}",
                    bean.articleAuthorName == null ? ""
                            : bean.articleAuthorName);
            tempString = tempString.replace("{ARTICLE_URL}",
                    "http://gate.baidu.com/tc?from=opentc&src="
                            + bean.articleLink);
            tempString = tempString.replace("{ARTICLE_DATE}",
                    new SimpleDateFormat("MM月dd日 HH:mm").format(bean.articleTime));
            String contentString = bean.content;
            if (contentString == null || contentString.trim().length() == 0) {
                contentString = "<div class='content-loading'>抱歉，加载内容失败。</div>";
            } else {
                Document document = Jsoup.parse(contentString);
                document.select("a").removeAttr("target");
                document.select("span").removeAttr("style");
                Elements imgs = document.select("img[src]");
                if (imgs != null && imgs.size() > 0) {
                    List<String> list = new ArrayList<String>();
                    for (Element ele : imgs) {
                        String imgurl = ele.attr("src");
                        ele.removeAttr("width").removeAttr("height");
                        String newFileName = FileUtil.getFileName(imgurl);
                        String path = RssConst.RSS_IMG_CACHE + newFileName;
                        File file = new File(path);
                        if (file.exists()) {
                            list.add(path);
                            ele.attr("src", RssConst.FILE_PREFIX + path);
                        } else {
                            list.add(imgurl);
                            // PicDownloadUtil.add2Queue(imgurl, path);
                        }
                    }
                    pics = list.toArray(new String[list.size()]);
                }
                contentString = document.toString();
                //Log.d(TAG, contentString);
            }
            tempString = tempString.replace("{ARTICLE_CONTENT}", contentString);
            buf.append(tempString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fisFileInputStream != null) {
                try {
                    fisFileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        processbar = (ProgressBar) findViewById(R.id.progressbar_updown);
        loadingProcessbar=(ProgressBar)findViewById(R.id.rss_loading_bar);

        // 使页面获得焦点
        webView.requestFocus();
        WebSettings ws = webView.getSettings();
        // 首先从cache加载，如果cache不存在则从网络加载
        ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        ws.setAppCacheEnabled(true);
        ws.setPluginsEnabled(true);

        ws.setAppCacheMaxSize(50 * 1024 * 1024);
        ws.setAllowFileAccess(true);
        ws.setAppCachePath(RssConst.APPROOT);
        ws.setDatabaseEnabled(true);
        ws.setDatabasePath(RssConst.APPROOT);
        // ws.setLightTouchEnabled(true);
        webView.setWebViewClient(new RssWebViewClient());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // super.onProgressChanged(view, newProgress);
                processbar.setProgress(newProgress);
                if (newProgress == 100) {
                    processbar.setVisibility(View.GONE);
                }
            }
        });
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.loadDataWithBaseURL(null, buf.toString(), "text/html", "UTF-8", null);

        webView.setOnTouchListener(new OnTouchListener() {
            private boolean flag = false;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    flag = true;
                } else if (flag && event.getAction() == MotionEvent.ACTION_UP) {
                    HitTestResult result = ((WebView) v).getHitTestResult();
                    int resultType = result.getType();
                    if (resultType == HitTestResult.IMAGE_TYPE) {
                        Intent intent = new Intent();
                        intent.setClass(getApplicationContext(), ImageSwitcherActivity.class);
                        intent.putExtra("list", pics);
                        intent.putExtra("rssTitle", rssTitle);
                        intent.putExtra("imgDIR", RssConst.RSS_IMG_CACHE);
                        int index = 0;
                        int len = RssConst.FILE_PREFIX.length();
                        String extra = result.getExtra();
                        String extraStr = "";
                        if (extra.startsWith("http")) {
                            extraStr = extra;
                        } else {
                            extraStr = extra.substring(len);
                        }
                        Log.d(TAG, "extra=" + extraStr);
                        Log.d(TAG, "pics size=" + pics.length);
                        for (String picUrl : pics) {
                            // String path = picUrl.substring(len);
                            if (extraStr.equals(picUrl)) {
                                break;
                            }

                            index++;
                        }

                        if (index >= pics.length) {
                            Toast.makeText(getApplicationContext(), "图片不能正常浏览", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            intent.putExtra("index", index);
                            startActivity(intent);
                        }
                    }
                    flag = false;
                } else {
                    flag = false;
                }
                return false;
            }
        });


    }



    private class RssWebViewClient extends WebViewClient {
        // 在点击请求的是链接是才会调用，重写此方法返回true表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边。
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG,"load url="+url);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            processbar.setVisibility(View.VISIBLE);
            loadingProcessbar.setVisibility(View.VISIBLE);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TextView tv = (TextView) findViewById(R.id.loadingMsg);
            // tv.setVisibility(View.GONE);
            loadingProcessbar.setVisibility(View.INVISIBLE);
            super.onPageFinished(view, url);
        }

        // 在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
        @Override
        public void onLoadResource(WebView view, String url) {
            // Log.d(TAG, "URL=" + url);
            super.onLoadResource(view, "http://gate.baidu.com/tc?from=opentc&src=" + url);
        }

        @Override
        public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
            super.onTooManyRedirects(view, cancelMsg, continueMsg);
        }

        @Override
        public void onReceivedError(WebView view,
                                    int errorCode,
                                    String description,
                                    String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            super.onFormResubmission(view, dontResend, resend);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view,
                                              HttpAuthHandler handler,
                                              String host,
                                              String realm) {
            super.onReceivedHttpAuthRequest(view, handler, host, realm);
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            return super.shouldOverrideKeyEvent(view, event);
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            super.onUnhandledKeyEvent(view, event);
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            super.onScaleChanged(view, oldScale, newScale);
        }
    }

    private final class MyJavaScript {
        public void openDetailPage() {
            Log.d(TAG,"url="+articleLink);
            Log.d(TAG,"title="+rssTitle);
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), RssReaderDetail.class);
            intent.putExtra("url", articleLink);
            intent.putExtra("title", rssTitle);
            startActivity(intent);
        }
    }

}
